<template>
  <div>
    <v-edit :title="init?.isAdd ? '产品新增' : '产品浏览'" :init="comm" :infos="info" @reset="reset" @save="save" @close="close"
      :rules="rules">
      <template #formItem>
        <div class="flex two-col-third-row intro-y">
          <div style="flex: 1">
            <wde-tree-select label="所属分类" prop="catCode" v-model="info.catCode" :options="categoryTree"
              :checkStrictly="true" />
            <!-- <wde-select label="一级分类" prop="cateMainKey" v-model="info.cateMainKey" :options="mainList"/>
            <wde-select label="二级分类" prop="cateSubKey" v-model="info.cateSubKey" :options="subList"/>
            <wde-select label="三级分类" prop="cateDetailKey" v-model="info.cateDetailKey" :options="detailList"/> -->
          </div>
          <div style="flex: 1">
            <el-form-item label="二维码" prop="qrCode">
              <el-upload action="#" list-type="picture-card" :auto-upload="true" :http-request="qrCodeHttpRequest"
                multiple v-model:file-list="qrCodeFileList" :class="{ 'hide': qrCodeFileList.length >= 1 }" :limit="1">
                <el-icon>
                  <Plus />
                </el-icon>

                <template #file="{ file }">
                  <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                        <el-icon><zoom-in /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </div>
        </div>
        <div class="one-col intro-y">
          <wde-input label="企业" prop="companyName" v-model="info.companyName" />
        </div>
        <div class="one-col intro-y">
          <wde-input label="名称" prop="productName" v-model="info.productName" />
        </div>
        <div class="one-col intro-y">
          <wde-input label="型号" prop="model" v-model="info.model" />
        </div>
        <div class="one-col intro-y">
          <wde-input label="技术指标" prop="kdj" v-model="info.kdj" type="textarea" />
        </div>
        <div class="one-col intro-y">
          <wde-input label="用途" prop="purpose" v-model="info.purpose" type="textarea" />
        </div>
        <div class="one-col intro-y">
          <wde-input label="案例" prop="case" v-model="info.case" type="textarea" />
        </div>
        <div class="one-col intro-y">
          <!--          <wde-files label="相关文件" v-model="fileList" />-->
          <el-form-item label="图片" prop="prop">
            <el-upload action="#" list-type="picture-card" :auto-upload="true" :http-request="httpRequest" multiple
              v-model:file-list="fileList">
              <el-icon>
                <Plus />
              </el-icon>

              <template #file="{ file }">
                <div>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <el-icon><zoom-in /></el-icon>
                    </span>
                  </span>
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </div>
        <div class="one-col intro-y">
          <wde-input label="视频链接" prop="videoUrl" v-model="info.videoUrl" />
        </div>
        <!--        <div class="one-col intro-y">-->
        <!--          &lt;!&ndash;          <wde-files label="相关文件" v-model="fileList" />&ndash;&gt;-->
        <!--          <el-form-item label="二维码" prop="qrCode">-->
        <!--            <el-upload action="#"-->
        <!--                       list-type="picture-card"-->
        <!--                       :auto-upload="true"-->
        <!--                       :http-request="qrCodeHttpRequest"-->
        <!--                       multiple-->
        <!--                       :file-list="qrCodeFileList"-->
        <!--                       v-model="qrCodeFileList"-->
        <!--                       :limit="1">-->
        <!--              <el-icon>-->
        <!--                <Plus/>-->
        <!--              </el-icon>-->

        <!--              <template #file="{ file }">-->
        <!--                <div>-->
        <!--                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>-->
        <!--                  <span class="el-upload-list__item-actions">-->
        <!--            <span-->
        <!--                class="el-upload-list__item-preview"-->
        <!--                @click="handlePictureCardPreview(file)"-->
        <!--            >-->
        <!--              <el-icon><zoom-in/></el-icon>-->
        <!--            </span>-->
        <!--            <span-->
        <!--                v-if="!disabled"-->
        <!--                class="el-upload-list__item-delete"-->
        <!--                @click="handleDownload(file)"-->
        <!--            >-->
        <!--              <el-icon><Download/></el-icon>-->
        <!--            </span>-->
        <!--            <span-->
        <!--                v-if="!disabled"-->
        <!--                class="el-upload-list__item-delete"-->
        <!--                @click="qrCodeHandleRemove(file)"-->
        <!--            >-->
        <!--              <el-icon><Delete/></el-icon>-->
        <!--            </span>-->
        <!--          </span>-->
        <!--                </div>-->
        <!--              </template>-->
        <!--            </el-upload>-->
        <!--          </el-form-item>-->
        <!--        </div>-->
        <!-- <div class="two-col intro-y">
          <wde-price label="金额(万元)" v-model="info.price" />
        </div>
        <div class="two-col intro-y">
          <wde-muti-select label="等级" v-model="info.levels" :options="options" />
        </div>
        <div class="two-col intro-y">
          <wde-select label="项目类型" v-model="info.type" :options="options" />
          <wde-muti-select label="等级" v-model="info.levels" :options="options" />
        </div>
        <div class="two-col intro-y">
          <wde-date label="计划开始时间" dateType="date" v-model="info.date" />
        </div>
        <div class="two-col intro-y">
          <wde-switch label="是否激活" v-model="info.isActive" />
        </div> -->
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </template>
    </v-edit>
  </div>
</template>

<script setup>
import { ref, toRefs, watch, getCurrentInstance, onMounted, computed } from "vue";
import { useEditLogic } from "@/views/base/useEditLogic";
import * as $api from "@/api/api.js";
import { ElMessage } from 'element-plus'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { postFile } from "@/utils/http";
import { ProductCompanyQueryOne, ProductQueryOne } from "@/api/api.js";
import { forEach } from "lodash";

const { proxy } = getCurrentInstance();
const emit = defineEmits(["close"]);

const props = defineProps({
  args: {
    type: Object,
    default: () => null,
  },
  init: {
    type: Object,
    default: () => null,
  },
});
// 使用 toRefs 解构 props
const { init } = toRefs(props);
const info = ref({
  catCode: "",
  userKey: "",
  companyKey: "",
  productKey: "",
  productName: "",
  model: "",
  kdj: "",
  case: "",
  qrCode: "",
  videoUrl: "",
  purpose: "",
  qrCodeUrl: "",
  images: [],
})
const fileList = ref([]);
const qrCodeFileList = ref([]);
const url = ref(`/api/SY_File/Upload`);
const userKey = ref(localStorage.getItem("userKey"));
const mainList = ref([]);
const subList = ref([]);
const detailList = ref([]);
const equtStateList = ref([]);
const categoryTree = ref([]);
const rules = ref({
  cateMainKey: [
    { required: true, message: "请输入一级分类", trigger: "blur" },
  ],
  companyName: [
    { required: true, message: "请输入企业", trigger: "blur" },
  ],
  productName: [
    { required: true, message: "请输入名称", trigger: "blur" },
  ],
  model: [
    { required: true, message: "请输入型号", trigger: "blur" },
  ],
  kdj: [
    { required: true, message: "请输入技术指标", trigger: "blur" },
  ],
  purpose: [
    { required: true, message: "请输入用途", trigger: "blur" },
  ],
});

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const getCategoryTree = () => {
  $api.CategoryQueryTree({}).then((res) => {
    categoryTree.value = formatTreeData(res.children);
  });
};

const formatTreeData = (data) => {
  return data.map(item => ({
    value: item.catCode,
    label: item.catName,
    children: item.children ? formatTreeData(item.children) : null
  }));
};
const handleRemove = (file) => {
  console.log(file);
  // 在 fileList 中删除指定的文件
  const index = fileList.value.indexOf(file);
  if (index !== -1) {
    fileList.value.splice(index, 1); // 从 fileList 中移除文件
  }
}
const qrCodeHandleRemove = (file) => {
  console.log(file);
  // 在 fileList 中删除指定的文件
  const index = qrCodeFileList.value.indexOf(file);
  if (index !== -1) {
    qrCodeFileList.value.splice(index, 1); // 从 fileList 中移除文件
  }
}
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleDownload = (file) => {
  console.log(file)
}

const httpRequest = (item) => {
  if (item && item.file) {
    // 先清除fileList中重复的文件（避免重复添加）
    const existingFileIndex = fileList.value.findIndex(f => f.name === item.file.name);
    if (existingFileIndex !== -1) {
      fileList.value.splice(existingFileIndex, 1); // 如果文件已经存在，就移除它
    }
    postFile(url.value, item.file)
      .then((file) => {
        if (file) {
          console.log("=>(Edit.vue:175) file", file);
          // files.value.push(file);
          // fileList.value.push(file);
          // 构造新的文件对象以匹配 el-upload 需要的格式
          const uploadedFile = {
            name: file.name || item.file.name || "",
            url: `${import.meta.env.VITE_APP_API}/${file.fileUrl}`, // 确保服务器返回的响应中有url字段
            fileUrl: file.fileUrl,
            fileName: file.fileName,
          };

          fileList.value.push(uploadedFile); // 更新 fileList
          ElMessage({
            message: "上传成功！",
            type: "success",
          });
        } else {
          // props.$messageError("未返回文件信息");
          ElMessage.error('上传失败');
        }
      })
      .catch((err) => {
        props.$messageError(err);
      });
  }
};
const qrCodeHttpRequest = (item) => {
  if (item && item.file) {
    // 先清除fileList中重复的文件（避免重复添加）
    const existingFileIndex = qrCodeFileList.value.findIndex(f => f.name === item.file.name);
    if (existingFileIndex !== -1) {
      qrCodeFileList.value.splice(existingFileIndex, 1); // 如果文件已经存在，就移除它
    }
    postFile(url.value, item.file)
      .then((file) => {
        if (file) {
          console.log("=>(Edit.vue:175) file", file);
          // files.value.push(file);
          // fileList.value.push(file);
          // 构造新的文件对象以匹配 el-upload 需要的格式
          const uploadedFile = {
            name: file.name || item.file.name || "",
            url: `${import.meta.env.VITE_APP_API}/${file.fileUrl}`, // 确保服务器返回的响应中有url字段
            fileUrl: file.fileUrl,
            fileName: file.fileName
          };

          qrCodeFileList.value.push(uploadedFile); // 更新 fileList
          ElMessage({
            message: "上传成功！",
            type: "success",
          });
        } else {
          // props.$messageError("未返回文件信息");
          ElMessage.error('上传失败');
        }
      })
      .catch((err) => {
        props.$messageError(err);
      });
  }
};
onMounted(
  () => {
    getEquiStateList();
  }
)
const queryOne = () => {
  $api.ProductQueryOne({
    userKey: userKey.value,
    key: init.value.productKey
  }).then((res) => {
    res.images.forEach((e) => {
      fileList.value.push({
        name: e,
        url: `${import.meta.env.VITE_APP_API}/UploadFilePath/${e}`,
        fileUrl: e,
        fileName: e,
      });
    })
    qrCodeFileList.value.push(
      {
        name: res.qrCode,
        url: `${import.meta.env.VITE_APP_API}/UploadFilePath/${res.qrCode}`,
        fileUrl: res.qrCode,
        fileName: res.qrCode,
      }
    )
  });
};
const getMainList = () => {
  $api.CategoryReferMain({}).then((res) => {
    mainList.value = res.map(e => {
      return {
        value: e.cateMainKey,
        label: e.cateMainName,
      };
    });
  });
};
const getSubList = () => {
  $api.CategoryReferSub({
    userKey: userKey.value,
    key: info.value.cateMainKey
  }).then((res) => {
    subList.value = res.map(e => {
      return {
        value: e.cateSubKey,
        label: e.cateSubName,
      };
    });
  });
};
const getDetailList = () => {
  $api.CategoryReferDetail({
    userKey: userKey.value,
    key: info.value.cateSubKey
  }).then((res) => {
    detailList.value = res.map(e => {
      return {
        value: e.cateDetailKey,
        label: e.cateDetailName,
      };
    });
  });
}
const getEquiStateList = () => {
  $api.ReferDict({
    plantKey: "",
    userKey: userKey.value,
    key: "10"
  }).then((res) => {
    equtStateList.value = res.subs.map(item => {
      return {
        value: item.dictID,
        label: item.dictName,
      }
    });
  });
};
const buildAdd = () => {
  console.log(fileList.value)
  info.value.userKey = localStorage.getItem("userKey");
  info.value.images = fileList.value.map(e => e.fileName);
  info.value.qrCode = qrCodeFileList.value.length > 0 ? qrCodeFileList.value[0].fileName : "";
  console.log(info.value.imageUrls)
  return $api.ProductCompanyInsert(info.value);
  // 构建新增逻辑
};

const buildUpdate = () => {
  info.value.images = fileList.value.map(e => e.fileName);
  info.value.qrCode = qrCodeFileList.value.length > 0 ? qrCodeFileList.value[0].fileName : "";
  return $api.ProductCompanyUpdate(info.value);
  // return $api.BATeacherUpdate(info.value);
};
const resetAdd = () => {
  proxy.$propsEmpty(info.value);
  // proxy.$propsCopy(info.value, props.init);
};
const resetUpdate = () => {
  proxy.$propsCopy(info.value, props.init);
};
const clearInfo = () => {
  proxy.$propsEmpty(info.value);
};

const close = () => {
  fileList.value = [];
  qrCodeFileList.value = [];
  emit("close");
};
const { loading, comm, isView, reset, save, VEdit } = useEditLogic(
  init,
  info,
  resetAdd,
  resetUpdate,
  clearInfo,
  buildAdd,
  buildUpdate,
  close
);
watch(
  () => comm,
  (newVal) => {
    console.log(newVal);
  }
);
watch(
  () => props.init,
  (newVal) => {
    if (newVal) {
      getMainList();
      queryOne();
      getCategoryTree();
    }
  }
);
watch(
  () => info.value.cateMainKey,
  (newVal) => {
    console.log("=>(Edit3.vue:159) newVal", newVal);
    getSubList();
  }
)
watch(
  () => info.value.cateSubKey,
  (newVal) => {
    console.log("=>(Edit3.vue:159) newVal", newVal);
    getDetailList();
  }
)
</script>

<style lang="scss" scoped>
:deep().hide .el-upload--picture-card {
  display: none;
}
</style>